package chuangyi.com.org.DOMIHome.Utils;

import android.net.Uri;
import android.util.Log;

import com.solidfire.gson.Gson;
import com.solidfire.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zxh on 16/10/29.
 */

public class HttpUtil {

    public static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }

    //    public static String ServerAddress = "http://test.wldsart.com";
    public static String ServerAddress = "https://dm.zhonghouqianyuan.com";
    private static OkHttpClient client = getClient();
    private static Gson gson;

    static {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(String.class, new StringConverter());
        gson = builder.create();
    }

    static OkHttpClient getClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(60, TimeUnit.SECONDS);
        builder.sslSocketFactory(createSSLSocketFactory());
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder.build();
    }

    /**
     * 异步GET请求方式
     *
     * @param path       URL绝对路径（不包含域名）
     * @param parameters 参数列表
     * @param callback   请求完成时的回调
     * @return
     */
    public static void getAsync(String path, Map<String, String> parameters, Callback callback) {
        StringBuilder builder = new StringBuilder();
        if (parameters != null) {
            builder.append("?");
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                builder.append(entry.getKey() + "=" + Uri.encode(entry.getValue()) + "&");
            }
            builder.delete(builder.length() - 1, builder.length() - 1);
        }
        String url = ServerAddress + path + builder.toString();
        Request request = new Request.Builder().url(url).get().build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * 异步POST请求方式
     *
     * @param path       URL绝对路径（不包含域名）
     * @param parameters 参数列表
     * @param callback   请求完成时的回调
     * @return
     */
    public static void postAsync(String path, Map<String, String> parameters, Callback callback) {
        FormBody body = null;
        if (parameters != null) {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
            body = builder.build();
        }
        String url = ServerAddress + path;
        Request request = new Request.Builder().url(url).post(body).build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * 同步GET请求方式
     *
     * @param path       URL绝对路径（不包含域名）
     * @param parameters 参数列表
     * @return
     */
    public static RequestResult get(String path, Map<String, String> parameters) {
        FormBody body = null;
        StringBuilder builder = new StringBuilder();
        if (parameters != null) {
            builder.append("?");
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                builder.append(entry.getKey() + "=" + Uri.encode(entry.getValue()) + "&");
            }
            builder.delete(builder.length() - 1, builder.length());
        }
        String url = ServerAddress + path + builder.toString();
        Request request = new Request.Builder().url(url).get().build();
        RequestResult result = new RequestResult();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String info = response.body().string();
                result = gson.fromJson(info, RequestResult.class);
                result.setInfo(info);
            } else {
                result.setCode("error");
                result.setMsg("向服务器发送请求失败");
            }
        } catch (Exception ex) {
            result.setCode("exception");
            result.setMsg("请检查网络连接是否正常");
        }
        return result;
    }

    /**
     * 同步POST请求方式
     *
     * @param path       URL绝对路径（不包含域名）
     * @param parameters 参数列表
     * @return
     */
    public static RequestResult post(String path, Map<String, String> parameters) {
        FormBody body = null;
        if (parameters != null) {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
            body = builder.build();
        }
        String url = ServerAddress + path;
        Request request = new Request.Builder().url(url).post(body).build();
        RequestResult result = new RequestResult();
//        Type type = new TypeToken<RequestResult>() {}.getType();
        try {
            Response response = client.newCall(request).execute();
            Log.e("Http", response.body().string());
            if (response.isSuccessful()) {
                String info = response.body().string();
                result = gson.fromJson(info, RequestResult.class);
                result.setInfo(info);
            } else {
                result.setCode("error");
                result.setMsg("向服务器发送请求失败");
            }
        } catch (Exception ex) {
            Log.e("Http", ex.getMessage(), ex);
            result.setCode("exception");
            result.setMsg("请检查网络连接是否正常");
        }
        return result;
    }

    public static <T> T fromJson(String json, Type typeOfT) {
        return gson.fromJson(json, typeOfT);
    }
}
